'use strict';

const {Service} = require('ee-core');
// 框架提供的数据库对象
// ee-core:v2.0.3
const Storage = require('ee-core/storage');
const _ = require('lodash');

/**
 * 数据存储
 * @class
 */
class StorageSQLiteService extends Service {

    constructor(ctx) {
        super(ctx);

        // sqlite数据库
        let neuronSQLiteOptions = {
            driver: 'sqlite',
            default: {
                timeout: 6000,
                verbose: console.log // 打印sql语法
            }
        }
        this.neuronSqliteDB = Storage.connection('sqlite-neuron.db', neuronSQLiteOptions);
    }


    async executeSqlOfSQLite(sql, data, isTransaction = false) {
        const res = this.neuronSqliteDB.db.prepare(sql);
        //查询
        if (sql.trim().toLowerCase().indexOf('select') == 0) {
            if (data) {
                return res.all(data)
            } else {
                return res.all()
            }
        } else {
            if (isTransaction) {
                this.neuronSqliteDB.db.transaction((data) => {
                    return res.run(data)
                })
            } else {
                return res.run(data)
            }

        }
    }

    /**
     * 新增记录
     * @param table 表
     * @param data 数据
     * @returns {Promise<boolean>}
     */
    async insertSQLite(table, data) {
        let sqlSuffix=this.dataConvertInsertColumnSuffix(data);
        if(sqlSuffix.length<0){
            return false;
        }
        let sql=`INSERT INTO ${table} ${sqlSuffix};`
        console.log('新增====>',sql)
        return this.executeSqlOfSQLite(sql, data)
    }

    /**
     * 更新记录
     * @param table 表
     * @param data 待更新数据
     * @param conditionData 更新条件
     * @returns {Promise<boolean>}
     */
    async updateSQLiteByCondition(table, data,conditionData) {
        let columnArray=this.dataConvertColumnArray(data,'=@');
        if(columnArray.length<0){
            return false;
        }
        let conditionColumnArray=this.dataConvertColumnArray(conditionData,'=@');
       let condition = columnArray.join(',')
        let sql=`UPDATE ${table} SET  ${condition} `
        if((await conditionColumnArray).length>0){
            sql=sql+`${conditionColumnArray.join(' and ')} ;`
        }else {
                sql=sql+';'
        }
        console.log('修改====>',sql)
        return this.executeSqlOfSQLite(sql, data)
    }

    /**
     * 删除记录
     * @param table 表
     * @param conditionData 查询条件
     * @returns {Promise<boolean>}
     */
    async deleteSQLiteByCondition(table, conditionData) {
        let columnArray=this.dataConvertColumnArray(conditionData,'=@');
        if(columnArray.length<0){
            return false;
        }
        let condition = columnArray.join(',')
        let sql=`DELETE FROM ${table}`
        if(condition.trim().length>0){
            sql=sql+` WHERE ${condition} ;`
        }else {
            sql=sql+';'
        }
        console.log('删除====>',sql)
        return this.executeSqlOfSQLite(sql, conditionData)
    }

    /**
     * 查询数据
     * @param table 表名
     * @param data 对象
     * @param column 列
     * @returns {Promise<Object>}
     */
    async selectSQLite(table, data, ...column) {
        let columnStr = '*'
        if (column && column.length > 0) {
            columnStr = column.join(',')
        }
        let condition = ''
        if (data && data.length > 0) {
            let oneCondition = this.dataConvertColumnArray(data,'=@')
            condition = oneCondition.join(' and ')
        }
        let sql = `select ${columnStr} from ${table} `
        if (condition && condition.length > 0) {
            sql = sql + ` where ${condition} ;`
        }else {
            sql=sql+';'
        }
        console.log('查询====>',sql)
        return this.executeSqlOfSQLite(sql, data)
    }

    /**
     * 查询、修改、删除可用
     * data对象转换为字段信息
     * @param data 对象
     * @param symbol 分割字符
     * @returns {Promise<[]>}
     */
    async dataConvertColumnArray(data,symbol){
        let columnArray = []
        if (data && data.length > 0) {
            Object.keys(data).forEach(key => {
                let oneColumn = key + symbol + key
                columnArray.push(oneColumn)
            })
        }
        return columnArray
    }

    /**
     * 对象转Insert Sql 后缀
     * @param data 对象
     * @returns {Promise<string>}
     */
    async dataConvertInsertColumnSuffix(data){
        let insertSqlSuffix = ''
        if (data && data.length > 0) {
            let columnKeyArray=[]
            let columnValueArray=[]
            Object.keys(data).forEach(key => {
                columnKeyArray.push(key)
                columnValueArray.push('@'+key)
            })
            insertSqlSuffix=`(${columnKeyArray.join(',')})  VALUES  (${columnValueArray.join(',')})`
        }
        return insertSqlSuffix
    }



}

StorageSQLiteService.toString = () => '[class StorageSQLiteService]';
module.exports = StorageSQLiteService;
